/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EventGeneratorsConfigPanel.java
 *
 * Created on Dec 23, 2010, 6:27:03 PM
 */
package com.wordpress.salaboy.sensor.ui;

import com.intel.bluetooth.BlueCoveConfigProperties;
import com.intel.bluetooth.BlueCoveImpl;
import com.wordpress.salaboy.model.CityEntities;
import com.wordpress.salaboy.messaging.MessageConsumerWorker;
import com.wordpress.salaboy.messaging.MessageConsumerWorkerHandler;
import com.wordpress.salaboy.model.Ambulance;
import com.wordpress.salaboy.model.messages.patient.HeartBeatMessage;
import com.wordpress.salaboy.sensor.SensorMessageProducer;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import motej.Mote;
import motej.StatusInformationReport;
import motej.event.AccelerometerEvent;
import motej.event.AccelerometerListener;
import motej.event.CoreButtonEvent;
import motej.event.CoreButtonListener;
import motej.event.MoteDisconnectedEvent;
import motej.event.MoteDisconnectedListener;
import motej.event.StatusInformationListener;
import motej.request.ReportModeRequest;
import com.wordpress.salaboy.sensor.wii.SimpleMoteFinder;

/**
 * @author salaboy
 * @author esteban
 */
public class WiiConfigPanel extends javax.swing.JPanel {

    private SensorMessageProducer messageProducer;
    
    private MessageConsumerWorker heartBeatReceivedWorker;
    
    private boolean offlineMode;

    /** Creates new form EventGeneratorsConfigPanel */
    public WiiConfigPanel(SensorMessageProducer messageProducer, boolean offlineMode) {
        this.messageProducer = messageProducer;

        this.setOfflineMode(offlineMode);
        
        initComponents();

        JComboBox combo = new JComboBox();
        Collection<List<Ambulance>> ambulances = CityEntities.ambulances.values();
        for (List<Ambulance> listOfAmbulances : ambulances) {
            for (Ambulance ambulance : listOfAmbulances) {
                String item = "Ambulance - " + ambulance.getId();
                combo.addItem(item);
            }
        }
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnWiiMoteLookup = new javax.swing.JButton();
        btnStopWiiMoteLookup = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        wiiMoteIdjTextField = new javax.swing.JTextField();
        btnListDevices = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        outputjTextArea = new javax.swing.JTextArea();

        setName("Wii Mote"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Wii Mote Bindings", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        btnWiiMoteLookup.setText("Start WiiMote Binding");
        btnWiiMoteLookup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnWiiMoteLookupActionPerformed(evt);
            }
        });

        btnStopWiiMoteLookup.setText("Stop WiiMote");
        btnStopWiiMoteLookup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStopWiiMoteLookupActionPerformed(evt);
            }
        });

        jLabel1.setText("Wii Mote Bluetooth Id: ");

        wiiMoteIdjTextField.setText("8C56C54923CA");

        btnListDevices.setText("List Devices");
        btnListDevices.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnListDevicesActionPerformed(evt);
            }
        });

        jButton1.setText("Clear");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnListDevices, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(wiiMoteIdjTextField))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(btnWiiMoteLookup)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnStopWiiMoteLookup, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)))
                .addContainerGap(74, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(btnListDevices)
                .addGap(11, 11, 11)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(wiiMoteIdjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnWiiMoteLookup)
                    .addComponent(btnStopWiiMoteLookup)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Output", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        outputjTextArea.setColumns(20);
        outputjTextArea.setRows(5);
        jScrollPane2.setViewportView(outputjTextArea);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnWiiMoteLookupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnWiiMoteLookupActionPerformed
        // TODO add your handling code here:
        initWiiMote();


    }//GEN-LAST:event_btnWiiMoteLookupActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        outputjTextArea.setText("");
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnStopWiiMoteLookupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStopWiiMoteLookupActionPerformed
        // TODO add your handling code here:
        if (mote != null) {
            mote.disconnect();
        }
        if (simpleMoteFinder != null) {
            simpleMoteFinder.stopFind();
        }
        BlueCoveImpl.shutdown();
        BlueCoveImpl.shutdownThreadBluetoothStack();

        outputjTextArea.insert(System.currentTimeMillis() + " - Wii mote Disconnected By the user", 0);
    }//GEN-LAST:event_btnStopWiiMoteLookupActionPerformed

    private void btnListDevicesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnListDevicesActionPerformed
        // TODO add your handling code here:
        listDevices();

    }//GEN-LAST:event_btnListDevicesActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnListDevices;
    private javax.swing.JButton btnStopWiiMoteLookup;
    private javax.swing.JButton btnWiiMoteLookup;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea outputjTextArea;
    private javax.swing.JTextField wiiMoteIdjTextField;
    // End of variables declaration//GEN-END:variables
    private Mote mote = null;
    private SimpleMoteFinder simpleMoteFinder;

    private void listDevices() {
    }

    private void initWiiMote() {
        System.setProperty(BlueCoveConfigProperties.PROPERTY_JSR_82_PSM_MINIMUM_OFF, "true");

        simpleMoteFinder = new SimpleMoteFinder();
        mote = simpleMoteFinder.findMote(wiiMoteIdjTextField.getText());
        if (mote == null) {
            outputjTextArea.insert(System.currentTimeMillis() + " - Wii mote not found! \n", 0);

        } else {
            outputjTextArea.insert(System.currentTimeMillis() + " - Wii mote found! \n", 0);
        }
        AccelerometerListener<Mote> listener = new AccelerometerListener<Mote>() {

            @Override
            public void accelerometerChanged(AccelerometerEvent<Mote> evt) {
                if (offlineMode){
                    return;
                }
                if (evt.getY() > 225) {
                    try {
                        messageProducer.informMessage(evt.getY() - 235);
                    } catch (Exception ex) {
                        Logger.getLogger(WiiConfigPanel.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        };
        MoteDisconnectedListener<Mote> disconnectedListener = new MoteDisconnectedListener<Mote>() {

            @Override
            public void moteDisconnected(MoteDisconnectedEvent<Mote> mde) {
                outputjTextArea.insert(System.currentTimeMillis() + " - Wii MOTE DISCONECTED!!!!\n", 0);
            }
        };

        CoreButtonListener buttonListener = new CoreButtonListener() {

            public void buttonPressed(CoreButtonEvent cbe) {
                if (cbe.isButtonAPressed()) {
                    outputjTextArea.insert(System.currentTimeMillis() + " - Button A Pressed!\n", 0);
                }
                if (cbe.isButtonBPressed()) {
                    outputjTextArea.insert(System.currentTimeMillis() + " - Button B Pressed!\n", 0);
                }
            }
        };

        StatusInformationListener statusListener = new StatusInformationListener() {

            public void statusInformationReceived(StatusInformationReport sir) {
            }
        };
        //mote.addStatusInformationListener(statusListener);
        mote.setReportMode(ReportModeRequest.DATA_REPORT_0x31);
        mote.addMoteDisconnectedListener(disconnectedListener);
        mote.addAccelerometerListener(listener);
        mote.addCoreButtonListener(buttonListener);

    }
    
    private void initWorkers() {
        if (this.offlineMode){
            return;
        }
        //Heart Beat Received
        heartBeatReceivedWorker = new MessageConsumerWorker("heartBeatWiiMote", new MessageConsumerWorkerHandler<HeartBeatMessage>() {

            @Override
            public void handleMessage(HeartBeatMessage message) {
                outputjTextArea.insert(System.currentTimeMillis() + " - sended " + message.getHeartBeatValue() + " heartbeat\n", 0);
            }
        });

        heartBeatReceivedWorker.start();
    }
    
    private void stopWorkers() {
        if(heartBeatReceivedWorker != null ){
            heartBeatReceivedWorker.stopWorker();
            heartBeatReceivedWorker = null;
        }
    }

    public void setOfflineMode(boolean offlineMode) {
        this.offlineMode = offlineMode;
        
        if (this.offlineMode){
            this.stopWorkers();
        } else{
            this.stopWorkers();
            this.initWorkers();
        }
        
    }
    
    
}
